/**
 * All rights reserved by www.xmerge.cn
 */
package net.xfok.info.ecup;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.xfok.rss.parser.Feed;
import net.xfok.rss.parser.Rss;
import net.xfok.string.filter.Filter;
import net.xfok.string.filter.Regex;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;

/**
 * @author YangHua
 *
 */
public class InfoService extends Service{
	private static String TAG="InfoService";
	private NotificationManager mNM;
	private SharedPreferences sp;
	private boolean notify;
	private int refresh;
	private int delete;

	@Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    public void onStart(Intent intent,int startId){
    	super.onStart(intent, startId);
    	Log.i(TAG, "onStart");
    	mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        sp=PreferenceManager.getDefaultSharedPreferences(this);
        notify=sp.getBoolean(InfoSettings.NOTIFY_KEY, true);
        refresh=Integer.parseInt(sp.getString(InfoSettings.REFRESH_KEY, InfoSettings.DEFAULT_VALUE));
        delete=Integer.parseInt(sp.getString(InfoSettings.DELETE_KEY, InfoSettings.DEFAULT_VALUE));
    	try{
    		if(refresh==1){
    			importInfo();
    		}else{
    			Log.i(TAG,"Manual Refresh!");
    		}
    		if(delete>0){
    			deleteInfo();
    		}else{
    			Log.i(TAG,"Manual Delete!");
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
    
    private void importInfo(){
    	if(InfoManage.checkNet(this)){
    		Rss rss=new Rss(InfoConstant.rss);
    		List<Feed> feeds=rss.getFeeds();
    		for(Feed feed:feeds){
    			InfoItem info=new InfoItem();
    			info.setTitle(InfoConstant.filter(feed.getTitle()));
    			info.setInfoId(String.valueOf(System.currentTimeMillis()));
    			info.setDate(InfoConstant.idf.format(new Date(feed.getPubDate())));
    			info.setContent(feed.getSummary());
    			Log.i(TAG, info.getInfoId());   			
    			if(!infoIsExit(info)){ 
    				InfoManage.addInfoItem(info, this);  
    				if(notify){
    					showNotification(info);
    				}
    			}else{
    				Log.i(TAG, info.getInfoId()+" is exit.");
    			}
    		}
    	}
    }
    
//    private void importInfo(){
//    	if(InfoManage.checkNet(this)){
//    		InfoParser infoParser=new InfoParser(InfoConstant.indexUrl);
//    		List<InfoItem> infoItems=infoParser.getInfoItems();
//    		for(InfoItem info:infoItems){
//    			Log.i(TAG, info.getInfoId());   			
//    			if(!infoIsExit(info)){  			
//	    			String infoUrl=InfoConstant.infoUrl+info.getInfoId();
//	    			String content=InfoConstant.genHtml(infoUrl);
//	    			if(content!=null){	    				
//	    				info.setContent(content);
//	    				InfoManage.addInfoItem(info, this);  
//	    				if(notify){
//	    					showNotification(info);
//	    				}
//	    			}
//    			}else{
//    				Log.i(TAG, info.getInfoId()+" is exit.");
//    			}
//    		}
//    	}
//    }
    
    private void deleteInfo(){
    	String today=InfoConstant.dateToStr(new Date());
    	switch (delete) {
		case 1:
			InfoManage.delInfoItem(today,this);
			break;
		case 2:
			InfoManage.delInfoItem(InfoConstant.getNextDay(today, -6), this);
			break;
		case 3:
			InfoManage.delInfoItem(InfoConstant.getNextDay(today,-30), this);
			break;
		default:
			break;
		}
    }
    
    private void showNotification(InfoItem info) {
    	Log.i(TAG, "show notification !");
        CharSequence text = info.getTitle()+" ["+info.getDate()+"]";
        Notification notification = new Notification(R.drawable.icon, text,System.currentTimeMillis());
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, InfoList.class), 0);
        notification.setLatestEventInfo(this, info.getTitle(),
                       text, contentIntent);
        mNM.notify(0, notification);
    }
    
    private boolean infoIsExit(InfoItem infoItem){
		 boolean result=false;
		 Uri infoUri = InfoItem.Info.CONTENT_URI;
//		 String selection=InfoItem.Info.INFO_COLUMN_INFO_ID+" = '"+infoItem.getInfoId()+"'";
		 String selection=InfoItem.Info.INFO_COLUMN_INFO_TITLE+" like '"+infoItem.getTitle()+"'";
	     Cursor cur = this.managedQuery(infoUri, InfoItem.Info.COLUMNS , selection, null, null );
	     if(cur.getCount()>0){
	    	 result=true;
	     }
	     return result;
	 }
    
    public void startManagingCursor(Cursor c) {
        synchronized (mManagedCursors) {
            mManagedCursors.add(new ManagedCursor(c));
        }
    }
    
    public final Cursor managedQuery(Uri uri,
            String[] projection,
            String selection,
            String[] selectionArgs,
            String sortOrder){
		Cursor c = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
		if (c != null) {
		startManagingCursor(c);
		}
		return c;
	}
    
    private final ArrayList<ManagedCursor> mManagedCursors =
        new ArrayList<ManagedCursor>();
   
    private static final class ManagedCursor {
        ManagedCursor(Cursor cursor) {
            mCursor = cursor;
            mReleased = false;
            mUpdated = false;
        }
        private final Cursor mCursor;
        private boolean mReleased;
        private boolean mUpdated;
    }
}
